import { determineUserRole } from './auth.js'
import fs from 'fs'
import path from 'path'

// 读取用户权限配置
const getUserPermissions = () => {
  try {
    const permissionsPath = path.join(process.cwd(), 'server', 'data', 'user-permissions.json')
    const data = fs.readFileSync(permissionsPath, 'utf8')
    return JSON.parse(data)
  } catch (error) {
    console.error('读取用户权限配置失败:', error)
    return {
      systemAdmins: ['admin', 'administrator', 'sgs_admin', 'apac\\Glenn_Gao', 'Glenn_Gao'],
      regularAdmins: [],
      users: []
    }
  }
}

// 保存用户权限配置
const saveUserPermissions = (permissions) => {
  try {
    const permissionsPath = path.join(process.cwd(), 'server', 'data', 'user-permissions.json')
    fs.writeFileSync(permissionsPath, JSON.stringify(permissions, null, 2), 'utf8')
    return true
  } catch (error) {
    console.error('保存用户权限配置失败:', error)
    return false
  }
}

// 模拟用户数据存储（在实际项目中应该使用数据库）
let users = [
  {
    username: 'Glenn_Gao',
    role: 'system',
    description: '系统管理员',
    active: true,
    createdAt: new Date().toISOString()
  },
]

// 获取用户列表
export const getUsers = async (ctx) => {
  try {
    const currentUser = ctx.state.user
    
    // 检查权限：只有管理员和系统管理员可以查看用户列表
    if (!currentUser || (currentUser.role !== 'admin' && currentUser.role !== 'system')) {
      ctx.status = 403
      ctx.body = { success: false, message: '权限不足' }
      return
    }

    // 获取权限配置
    const permissions = getUserPermissions()
    
    // 生成用户列表，包含实际权限信息
    const userList = []
    
    // 添加系统管理员
    permissions.systemAdmins.forEach((username, index) => {
      userList.push({
        id: `sys_${index}`,
        username,
        role: 'system',
        description: '系统管理员',
        active: true,
        createdAt: new Date().toISOString()
      })
    })
    
    // 添加普通管理员
    permissions.regularAdmins.forEach((username, index) => {
      userList.push({
        id: `admin_${index}`,
        username,
        role: 'admin',
        description: '管理员',
        active: true,
        createdAt: new Date().toISOString()
      })
    })
    
    // 添加普通用户
    permissions.users.forEach((username, index) => {
      userList.push({
        id: `user_${index}`,
        username,
        role: 'user',
        description: '普通用户',
        active: true,
        createdAt: new Date().toISOString()
      })
    })

    console.log('返回的用户列表:', JSON.stringify(userList, null, 2))
    
    ctx.body = {
      success: true,
      data: userList
    }
  } catch (error) {
    console.error('获取用户列表错误:', error)
    ctx.status = 500
    ctx.body = { success: false, message: '服务器内部错误' }
  }
}

// 更新用户角色
export const updateUserRole = async (ctx) => {
  try {
    const currentUser = ctx.state.user
    const { username, role } = ctx.request.body

    // 检查权限
    if (!currentUser || (currentUser.role !== 'admin' && currentUser.role !== 'system')) {
      ctx.status = 403
      ctx.body = { success: false, message: '权限不足' }
      return
    }

    // 管理员不能分配系统管理员角色
    if (currentUser.role === 'admin' && role === 'system') {
      ctx.status = 403
      ctx.body = { success: false, message: '管理员无法分配系统管理员权限' }
      return
    }

    // 不能修改自己的权限
    if (currentUser.username === username) {
      ctx.status = 400
      ctx.body = { success: false, message: '不能修改自己的权限' }
      return
    }

    if (!username || !role) {
      ctx.status = 400
      ctx.body = { success: false, message: '用户名和角色不能为空' }
      return
    }

    // 获取当前权限配置
    const permissions = getUserPermissions()
    
    // 从所有列表中移除用户
    permissions.systemAdmins = permissions.systemAdmins.filter(user => user !== username)
    permissions.regularAdmins = permissions.regularAdmins.filter(user => user !== username)
    permissions.users = permissions.users.filter(user => user !== username)
    
    // 根据新角色添加到相应列表
    switch (role) {
      case 'system':
        permissions.systemAdmins.push(username)
        break
      case 'admin':
        permissions.regularAdmins.push(username)
        break
      case 'user':
        permissions.users.push(username)
        break
      default:
        ctx.status = 400
        ctx.body = { success: false, message: '无效的角色类型' }
        return
    }
    
    // 保存配置
    if (saveUserPermissions(permissions)) {
      console.log(`用户 ${username} 的角色已更新为 ${role}`)
      ctx.body = {
        success: true,
        message: '用户权限更新成功',
        user: {
          username,
          role,
          description: role === 'system' ? '系统管理员' : role === 'admin' ? '管理员' : '普通用户',
          active: true
        }
      }
    } else {
      ctx.status = 500
      ctx.body = { success: false, message: '保存权限配置失败' }
    }
  } catch (error) {
    console.error('更新用户角色错误:', error)
    ctx.status = 500
    ctx.body = { success: false, message: '服务器内部错误' }
  }
}

// 添加新用户
export const addUser = async (ctx) => {
  try {
    const currentUser = ctx.state.user
    const { username, role = 'user', description } = ctx.request.body

    // 检查权限
    if (!currentUser || (currentUser.role !== 'admin' && currentUser.role !== 'system')) {
      ctx.status = 403
      ctx.body = { success: false, message: '权限不足' }
      return
    }

    // 管理员不能创建系统管理员
    if (currentUser.role === 'admin' && role === 'system') {
      ctx.status = 403
      ctx.body = { success: false, message: '管理员无法创建系统管理员账户' }
      return
    }

    // 验证输入
    if (!username || !username.trim()) {
      ctx.status = 400
      ctx.body = { success: false, message: '用户名不能为空' }
      return
    }

    if (!['user', 'admin', 'system'].includes(role)) {
      ctx.status = 400
      ctx.body = { success: false, message: '无效的用户角色' }
      return
    }

    // 获取当前权限配置
    const permissions = getUserPermissions()
    
    // 检查用户是否已存在
    const allUsers = [
      ...permissions.systemAdmins,
      ...permissions.regularAdmins,
      ...permissions.users
    ]
    
    if (allUsers.includes(username.trim())) {
      ctx.status = 400
      ctx.body = { success: false, message: '用户已存在' }
      return
    }
    
    // 根据角色添加到相应列表
    switch (role) {
      case 'system':
        permissions.systemAdmins.push(username.trim())
        break
      case 'admin':
        permissions.regularAdmins.push(username.trim())
        break
      case 'user':
        permissions.users.push(username.trim())
        break
      default:
        ctx.status = 400
        ctx.body = { success: false, message: '无效的角色类型' }
        return
    }
    
    // 保存配置
    if (saveUserPermissions(permissions)) {
      console.log(`新用户 ${username} 已创建，角色: ${role}`)
      
      ctx.body = {
        success: true,
        message: '用户创建成功',
        user: {
          username: username.trim(),
          role,
          description: description || (role === 'system' ? '系统管理员' : role === 'admin' ? '管理员' : '普通用户'),
          active: true
        }
      }
    } else {
      ctx.status = 500
      ctx.body = { success: false, message: '保存权限配置失败' }
    }
  } catch (error) {
    console.error('添加用户错误:', error)
    ctx.status = 500
    ctx.body = { success: false, message: '服务器内部错误' }
  }
}

// 删除用户
export const deleteUser = async (ctx) => {
  try {
    const currentUser = ctx.state.user
    const { username } = ctx.params || ctx.request.body

    // 检查权限
    if (!currentUser || (currentUser.role !== 'admin' && currentUser.role !== 'system')) {
      ctx.status = 403
      ctx.body = { success: false, message: '权限不足' }
      return
    }

    // 不能删除自己
    if (currentUser.username === username) {
      ctx.status = 400
      ctx.body = { success: false, message: '不能删除自己的账户' }
      return
    }

    if (!username) {
      ctx.status = 400
      ctx.body = { success: false, message: '用户名不能为空' }
      return
    }

    // 获取当前权限配置
    const permissions = getUserPermissions()
    
    // 检查用户是否存在并获取其角色
    let userRole = null
    if (permissions.systemAdmins.includes(username)) {
      userRole = 'system'
    } else if (permissions.regularAdmins.includes(username)) {
      userRole = 'admin'
    } else if (permissions.users.includes(username)) {
      userRole = 'user'
    }
    
    if (!userRole) {
      ctx.status = 404
      ctx.body = { success: false, message: '用户不存在' }
      return
    }

    // 检查目标用户权限：管理员不能删除系统管理员
    if (currentUser.role === 'admin' && userRole === 'system') {
      ctx.status = 403
      ctx.body = { success: false, message: '管理员无法删除系统管理员账户' }
      return
    }
    
    // 从所有列表中移除用户
    permissions.systemAdmins = permissions.systemAdmins.filter(user => user !== username)
    permissions.regularAdmins = permissions.regularAdmins.filter(user => user !== username)
    permissions.users = permissions.users.filter(user => user !== username)
    
    // 保存配置
    if (saveUserPermissions(permissions)) {
      console.log(`用户 ${username} 已被删除`)
      
      ctx.body = {
        success: true,
        message: '用户删除成功',
        deletedUser: {
          username,
          role: userRole
        }
      }
    } else {
      ctx.status = 500
      ctx.body = { success: false, message: '保存权限配置失败' }
    }
  } catch (error) {
    console.error('删除用户错误:', error)
    ctx.status = 500
    ctx.body = { success: false, message: '服务器内部错误' }
  }
}

// 获取当前用户信息
export const getCurrentUser = async (ctx) => {
  try {
    const currentUser = ctx.state.user
    
    if (!currentUser) {
      ctx.status = 401
      ctx.body = { success: false, message: '未登录' }
      return
    }

    ctx.body = {
      success: true,
      user: {
        username: currentUser.username,
        role: currentUser.role,
        permissions: {
          canAccessAdminFeatures: currentUser.role === 'admin' || currentUser.role === 'system',
          canAccessDffTest: currentUser.role === 'system',
          isSystemAdmin: currentUser.role === 'system',
          isRegularAdmin: currentUser.role === 'admin'
        }
      }
    }
  } catch (error) {
    console.error('获取当前用户信息错误:', error)
    ctx.status = 500
    ctx.body = { success: false, message: '服务器内部错误' }
  }
}